#include <model3d.h>
#include <stdio.h>
#include <stdlib.h>

#include <debug.h>

static const uint16_t size = 128;

static const uint16_t colors[ 8 ] = { 1, 2, 3, 4, 5, 6, 7, 8 };

int main( int argc, char *argv[] )
{
  if ( argc < 2 )
    {
      fprintf( stderr, "Missing filename!\n" );
      exit( -1 );
    }

  char *filename = argv[ 1 ];

  model3d_t *m = model3d_new( size, size, size );

  uint16_t i, j, k;

  uint16_t half = size / 2;

  for ( k=0; k < size; k++ )
    for ( i=0; i < size; i++ )
      for ( j=0; j < size; j++ )
	{
	  unsigned int region=-1;
	  if      ( ( i <  half ) && ( j <  half ) && ( k <  half ) )
	    region = 0;
	  else if ( ( i <  half ) && ( j <  half ) && ( k >= half ) )
	    region = 1;
	  else if ( ( i <  half ) && ( j >= half ) && ( k <  half ) )
	    region = 2;
	  else if ( ( i >= half ) && ( j <  half ) && ( k <  half ) )
	    region = 3;

	  else if ( ( i >= half ) && ( j >= half ) && ( k >= half ) )
	    region = 4;
	  else if ( ( i >= half ) && ( j >= half ) && ( k <  half ) )
	    region = 5;
	  else if ( ( i >= half ) && ( j <  half ) && ( k >= half ) )
	    region = 6;
	  else if ( ( i <  half ) && ( j >= half ) && ( k >= half ) )
	    region = 7;
	  else
	    {
	      err( "Unmapped region: %d, %d %d.\n", i, j, k );
	      return -1;
	    }

	  VOXEL_AT( m, i, j, k ) = colors[ region ];
	}

  FILE *fd = fopen( filename, "w" );
  if ( fd == NULL )
    {
      model3d_free( m );
      perror( "Could not open file" );
      return -1;
    }

  fprintf( fd, "SCN\n%u %u %u\n1.0 1.0 1.0\n16\n", size, size, size );
  int n = fwrite( m->buffer, sizeof( *m->buffer ), size * size * size, fd );
  fclose( fd );

  model3d_free( m );

  if ( n != size * size * size )
    {
      fprintf( stderr, "Wrote just %d of %d desired!\n",
	       n, size * size * size );
    }


  return 0;
}
